package com.ray.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DeptReachBean;
import com.ray.bean.DutyBean;
import com.ray.bean.FeedingAndReportBean;
import com.ray.bean.InCountBean;
import com.ray.bean.MergeBean;
import com.ray.bean.OrderBean;
import com.ray.bean.ReportBean;
import com.ray.bean.ReturnWorkBean;
import com.ray.bean.TableData;
import com.ray.bean.TurnOverBea;
import com.ray.bean.TurnoverBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.ReturnWorkMapper;
import com.ray.pojo.MyUser;
import com.ray.util.ExceptionUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;

import net.sf.json.JSONArray;

@Service
//返修
public class ReturnWorkService {
	@Autowired
	ReturnWorkMapper returnWorkMapper;
	@Autowired
	WorkshopService workshopService;
	@Autowired
	OrderService orderService;


	public void insertReturnWork(String  reportArrayJSONStr) throws ServiceException {
		JSONArray jsonArray = JSONArray.fromObject(reportArrayJSONStr);//把String转换为 数组 
		List<ReportBean> list= (List<ReportBean>)JSONArray.toCollection(jsonArray, ReportBean.class);
		List<ReturnWorkBean> returnList=new ArrayList<ReturnWorkBean>();
		for(ReportBean reportBean:list) {
			//查询已报工合格数
			long sumQuite=workshopService.getqualified(reportBean);
			if(reportBean.getQualified()> sumQuite) {
				throw new ServiceException("返修数不能大于交接入库数"+sumQuite);
			}
			//获取已返修数量
			long returnSumQuite=returnWorkMapper.getqualified(reportBean);
			if((returnSumQuite+reportBean.getQualified())>sumQuite) {
				throw new ServiceException("已返修"+returnSumQuite+"个，最多还可返修"+(sumQuite-returnSumQuite)+"个");
			}
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
			reportBean.setTime(formatter.format(new Date())+" 0:00:00");//设置日期时间
			reportBean.setCompany(WeiXinParamesUtil.company);
			formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			String dateString = formatter.format(new Date());
//			MergeBean mergeBean=workshopService.getMergeBean(reportBean.getInWorkShop());
//			if(null!=mergeBean) {
//				reportBean.setInWorkShop(mergeBean.getMergeToWorkShop());
//			}
			ReturnWorkBean returnWorkBean =new ReturnWorkBean();
			returnWorkBean.setColor(reportBean.getColor());//设置返修颜色
			returnWorkBean.setMachining(reportBean.getMachining());//设置加工对象
			returnWorkBean.setOrderId(reportBean.getOrderId());//设置订单编号
			returnWorkBean.setReceiveWorkshop(reportBean.getWorkShopName());//设置接收车间
			returnWorkBean.setRepairWorkshop(reportBean.getUserWorkShop());//报修车间
			returnWorkBean.setRepairProcedure(reportBean.getUserProcedure());//报修工序
			returnWorkBean.setRepairUser(reportBean.getTouchPeople());//报修人
			returnWorkBean.setRepairTime(dateString);//报修时间
			returnWorkBean.setRepairCount(reportBean.getQualified());//设置报修数
			returnWorkBean.setIsFinish(0);//是否完成  0 未完成 1 完成
     //		returnWorkBean.setReturnOrder(returnOrder);//报修生成单号
			long sort=returnWorkMapper.getMaxSort()+1;
			reportBean.setSortKey(sort);
			reportBean.setTouchTime(dateString);
			returnList.add(returnWorkBean);
		}
		returnWorkMapper.insertReturnWork(returnList);
		returnWorkMapper.insertReport(list);
	}

	//返修报工
	public void returnWorkReport(ReportBean reportBean) throws ServiceException, CloneNotSupportedException {
		
		//先判断此订单是否有返修记录
		long returnWorkCount=returnWorkMapper.getReturnWorkByReportBean(reportBean);
		if(returnWorkCount<=0){
			throw new ServiceException("此订单明细没有返修记录");
		}
		//查询此车间入库数
	    long inCount=0;
	  //获取车间合并情况
	    String workShop=reportBean.getWorkShopName();
		MergeBean mergeBean=workshopService.getMergeBean(reportBean.getWorkShopName());
		if(null==mergeBean) {
			inCount=returnWorkMapper.getOrderInCount(reportBean);
		}else {
			workShop=mergeBean.getMergeToWorkShop();
			ReportBean reb=reportBean.clone();
			reb.setWorkShopName(mergeBean.getMergeToWorkShop());
			inCount=returnWorkMapper.getOrderInCount(reb);
		}
		
		//返修数与报工数
		FeedingAndReportBean feedingAndReportBean=new FeedingAndReportBean();
		feedingAndReportBean.setFeddingCount(returnWorkCount);
		feedingAndReportBean.setReportCount(returnWorkMapper.getReportCount(reportBean));

		long sort=returnWorkMapper.getMaxSort()+1;
		reportBean.setSortKey(sort);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
		reportBean.setTime(formatter.format(new Date())+" 0:00:00");//设置日期时间
		reportBean.setCompany(WeiXinParamesUtil.company);
		formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString = formatter.format(new Date());
		reportBean.setTouchTime(dateString);
		
		ArrayList<ReportBean> reportBeanList=new ArrayList<ReportBean>();
		//如果不是交接入库，判断是否交接入库
		if(!reportBean.getProcedur().equals("交接入库")) {
			if(inCount<=0) {
				throw new ServiceException(reportBean.getColor()+"在"+workShop+"车间还没有交接入库");
			}
			if(inCount<reportBean.getQualified()) {
				throw new ServiceException(reportBean.getColor()+"报工数不能大于"+workShop+"车间入库数"+inCount);
			}
			if(inCount-feedingAndReportBean.getReportCount()-reportBean.getQualified()<0) {
				throw new ServiceException(reportBean.getColor()+"已报工"+feedingAndReportBean.getReportCount()+"个，最多还可报工"+(inCount-feedingAndReportBean.getReportCount())+"个");
			}
			//如果是交接出库
			if(reportBean.getProcedur().equals("交接出库")) {
				if(null==mergeBean) {
					if(reportBean.getInWorkShop()==null||reportBean.getInWorkShop().equals("")) {
						throw new ServiceException("没有获取到接收车间");
					}
					if(reportBean.getWorkShopName().equals(reportBean.getInWorkShop())) {
						throw new ServiceException("出入库车间不能相同");
					}
					ReportBean inReportBean=reportBean.clone();
					inReportBean.setWorkShopName(inReportBean.getInWorkShop());
					inReportBean.setProcedur("交接入库");
					//接收车间已接收数
					long inCountTwo=returnWorkMapper.getOrderInCount(inReportBean);
					//如果接收数大于投料数
					mergeBean=workshopService.getMergeBean(inReportBean.getWorkShopName());
					if(mergeBean==null) {
						if(inReportBean.getQualified()>(feedingAndReportBean.getFeddingCount()-inCountTwo)) {
							throw new ServiceException(inReportBean.getColor()+"在"+inReportBean.getInWorkShop()+"车间已入库"+inCountTwo+"最多还可入库"+(feedingAndReportBean.getFeddingCount()-inCountTwo)+"个");
						}
						inReportBean.setSortKey(sort+1);
//						inList.add(inReportBean);
						reportBeanList.add(inReportBean);
//						returnWorkMapper.insertReport(inReportBean);
					}else {
						throw new ServiceException(inReportBean.getWorkShopName()+"车间已合并到"+workShop+"请选择此车间交接");
					}
				}else {
					throw new ServiceException("该车间已合并到"+workShop+"请选择此车间交接");
				}
			}
		}else {//如果是交接入库
			if(null==mergeBean) {
				//如果报工数大于投料数减掉已交接入库数（还可入库数）
				if(reportBean.getQualified()>(feedingAndReportBean.getFeddingCount()-inCount)) {
					throw new ServiceException(reportBean.getColor()+"已入库"+inCount+"最多还可入库"+(feedingAndReportBean.getFeddingCount()-inCount)+"个");
				}
			}else {
				throw new ServiceException("该车间已合并到"+workShop+"请选择此车间交接");
			}
		}
		reportBeanList.add(reportBean);
		returnWorkMapper.insertReport(reportBeanList);
	}

	public List<String> getFactoryReturn(String workShopName) {
		// TODO Auto-generated method stub
		return returnWorkMapper.getFactoryReturn(workShopName);
	}

	public List<String> getDeviceIdReturn(String workShopName) {
		// TODO Auto-generated method stub
		return returnWorkMapper.getDeviceIdReturn(workShopName);
	}

	public List<String>  getDeviceNameReturn(String workShopName) {
		// TODO Auto-generated method stub
		return returnWorkMapper.getDeviceNameReturn(workShopName);
	}

	public List<String> returnWorkColor(String machining, String orderId) {
		return returnWorkMapper.returnWorkColor(machining,orderId);
	}
	
    //获取达成率数据
	public List<DeptReachBean> getTotal(String date,String startDay, MyUser myUser) throws ParseException {
		date=date+" 00:00:00.000";
		startDay=startDay+" 00:00:00.000";
		int days=TimeAndUnix.getDateDays(startDay, date)+1;
		return returnWorkMapper.getTotal(date,startDay,days,myUser);
	}

	//获取车间人员工作效率
	public DatatablesViewPageBean<TableData> getTableData(Map map) throws ServiceException {
//		map=workshopService.workShopToId(map);
		int count=0;
		DatatablesViewPageBean<TableData> dtcpb=new DatatablesViewPageBean<TableData>();
		count=returnWorkMapper.getTableDataCount(map);
		dtcpb.setReturnData(returnWorkMapper.getTableData(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	public DatatablesViewPageBean<DutyBean> getDelayDate(Map map) {
//		map=workshopService.workShopToId(map);
		int count=0;
		DatatablesViewPageBean<DutyBean> dtcpb=new DatatablesViewPageBean<DutyBean>();
		count=returnWorkMapper.getDelayDateCount(map);
		dtcpb.setReturnData(returnWorkMapper.getDelayDate(map));
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count);
		return dtcpb;
	}

	public List<DutyBean> getSoonDelay(Map map) {
//		map =workshopService.workShopToId(map);
		return returnWorkMapper.getSoonDelay(map);
	}

	public List<DeptReachBean> getOnTime(Map map) {
		List<DeptReachBean> list=returnWorkMapper.getOnTime(map);
		if(null==list || list.size()<=0) {
			list=workshopService.deptReachNull(map);
		}
		return list;
	}


	public List<DeptReachBean> getSereven(Map map) {
//		map =workshopService.workShopToId(map);
		return returnWorkMapper.getSereven(map);
	}

	//获取每个车间周转量
	public List<TurnoverBean> getDeptTurnover(Map map) throws ServiceException {
//		map =workshopService.workShopToId(map);
		List<String> orderIdList=this.getWorkingOrder(map);//获取正在生产的订单号
		if(orderIdList.size()<=0||null==orderIdList) {
			throw new ServiceException("该车间没有正在生产"+map.get("machining").toString()+"的订单");
		}
		map.put("orderIdList", orderIdList);
		return returnWorkMapper.getDeptTurnover(map);
	}


	//获取正在生产的订单号
	private List<String> getWorkingOrder(Map map) {
		return returnWorkMapper.getWorkingOrder(map);
	}

	     //整理周转量数据
		public List<Map> getTrunover(Map mapParam) throws ServiceException {
//			mapParam =workshopService.workShopToId(mapParam);
			List<String> orderIdList=this.getWorkingOrder(mapParam);//获取正在生产的订单号
			if(orderIdList.size()<=0||null==orderIdList) {
				throw new ServiceException("该车间没有正在生产的"+mapParam.get("machining").toString()+"订单");
			}
			String workShopName=mapParam.get("workShop").toString();
			List<String> procedureList=workshopService.getWorkingProcedureName(mapParam);//得到工序名称
			List<Map> ListMap=new ArrayList<Map>();
	        //遍历正在生产的订单
			for(String orderId:orderIdList) {
				mapParam.put("orderId", orderId);
				//获取入库数
				long  inCount=returnWorkMapper.getInCount(mapParam);
				//获取合格数与不合格数
				List<TurnOverBea> turnList=returnWorkMapper.getTrunover(mapParam);
				OrderBean orderBean=orderService.getOrderByOrderId(orderId);
				//获取一个订单的周转量数据
				Map map=workshopService.getOneOrderTurnover(procedureList,inCount,turnList);
				map.put("orderId", orderId);//订单编号
				map.put("factoryId", orderBean.getFactoryId());//工厂型号
				map.put("keHu", orderBean.getCustomerId());//客户型号
				map.put("keHuOrder", orderBean.getCustomerOrderId());//客户订单号
				ListMap.add(map);
			}
			if(ListMap.size()>0) {
				Map sumMap=workshopService.getSumTurnover(procedureList,ListMap);
				ListMap.add(sumMap);
				Map<String,List<String>> procedureMap=new HashMap<String,List<String>>();
				procedureMap.put("procedureMap", procedureList);
				ListMap.add(procedureMap);
			}
			return ListMap;
		}

		//获取整厂周转量
		public long getFactoryTurnover(Map map) {
			//获取全厂在生产订单
			List<String> orderList=returnWorkMapper.getFactoryWorkingOrder(map);
			if(null==orderList || orderList.size()<=0) {
			   return 0;
			}
			//获取订单投料数
			long feddiingCouont=returnWorkMapper.getFeddingCount(orderList);
			//获取出库数
			long outCount=returnWorkMapper.getOutCount(orderList);
			long factoryTurnover=feddiingCouont-outCount;
			if(factoryTurnover>0) {
				return factoryTurnover;
			}
			return 0;
		}

	
		//获取订单生产情况（订单查询）
		public List<Map> getOrderWork(Map mapParam) throws ServiceException {
			Set<String> allSet=new HashSet<String>();
			List<DutyBean> dutyBeanList=returnWorkMapper.getOrderWork(mapParam);//得到所有订单报工数据
			Map<String,List<String>> orderListMap=new HashMap<String,List<String>>();
			if(dutyBeanList.size()<=0) {
				throw new ServiceException("查询的订单还未开始生产！");
			}
			List<String> workShopList=workshopService.getWorkshopName(mapParam);//得到车间名称
			orderListMap.put("order", workShopList);
			List<Map> xx=new ArrayList<Map>();//最终整理后的数据
			xx.add(orderListMap);
			for(DutyBean dutyBean:dutyBeanList) {//遍历得到所有订单
				allSet.add(dutyBean.getOrderId());
			}
			for(String str:allSet) {//遍历所有订单
				Map<String,List<DutyBean>> map=new HashMap<String,List<DutyBean>>();//用于存当前车间报工数据
				for(String workShop:workShopList) {//遍历所有车间
					List<DutyBean> listDuty=new ArrayList();//一个车间一个list
					for(DutyBean dutyBean:dutyBeanList) {//遍历所有数据
						//如果订单号与车间名称符合则存入数据
						if(dutyBean.getOrderId().equals(str)&&dutyBean.getWorkShopName().equals(workShop)) {
							listDuty.add(dutyBean);
						}
					}
					map.put(workShop, listDuty);
				}
				xx.add(map);
			}
			return xx;
		}

		//查询产能信息
		public List<Map> queryCapacity(String workshopName, String workingProcedureName, String titleList) {
			JSONArray jsonArray = JSONArray.fromObject(titleList);
			List<String> titleLists=jsonArray.subList(0, jsonArray.size());
			workshopName=workshopService.emptyToNull(workshopName);
			if(null==workshopName) {
				return null;
			}
			workingProcedureName=workshopService.emptyToNull(workingProcedureName);
			return returnWorkMapper.queryCapacity(workshopName,workingProcedureName,titleLists);
		}

		//获取车间七日周转量
		public List<DeptReachBean> serverTurnover(Map map) {
//			map=workshopService.workShopToId(map);
			return returnWorkMapper.serverTurnover(map);
		}

		//获取人员达成率
		public List<TableData> getPersonData(Map map) throws ServiceException {
//			map =workshopService.workShopToId(map);
			return returnWorkMapper.getPersonData(map);
		}

		//获取返修报工对象
		public List<String> getMachining(Map map) {
			return returnWorkMapper.getMachining(map);
		}
	
	

}
